package com.yls.except.controller;

import com.yls.except.task.RedisCash;
import com.yls.except.util.*;
import com.yls.except.util.exception.ExceptionHandle;
import com.yls.except.util.imgfile.ImgCompress;
import com.yls.except.util.imgfile.OssUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 上传图片
 *
 * @author xs
 * @version 1.0
 * @time 2016-1-30 下午5:17:38
 * @Description: {}
 */
@Controller
@RequestMapping(value = "uploadcontroller/")
public class UploadController extends ExceptionHandle {

    /**
     * 上传图片
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadimg.controller")
    public void uploadimg(HttpServletRequest req, HttpServletResponse resp,
                          @RequestParam MultipartFile[] upload, HttpSession session) throws IOException {
        List<Object> list = new ArrayList<Object>();
        String type = req.getParameter("type");
        String idCardSide = req.getParameter("idCardSide");
//        String token = req.getParameter("token");
//        long timestamp = new Date().getTime();
        String path = ""; // 返回路径
//        String imgtype = req.getParameter("imgtype"); // 图片类型
        String filename = "";
        String src = "/headmimg";
//        if (upload == null || "".equals(upload) || token == null
//                || "".equals(token)) {
//            GeneralResult.general(resp, list, 20001, 0); // 参数有误
//        } else if ("".equals(src) || src == null) {
//            GeneralResult.general(resp, list, 20001, 0);
//        } else {
        String realPath = session.getServletContext().getRealPath(src);
//        String filepath = ImgProperties.getimg("filepath");
//        String item = ImgProperties.getConstan("itemname");
//            token = HexString.decode(token);
//            token = HexString.removestr(token, 6, item, "");
        // 获取登录token
//            Map<String, String> userTokenMap = RedisCash.getMap("life" + token);
//            if (!StringIsempty.isNullMap(userTokenMap)) {
//                String uid = userTokenMap.get("uid");
//                String userType = userTokenMap.get("type");
//                long datetime = Long.parseLong(userTokenMap.get("time"));
//                long mistaketime = timestamp - datetime;
//                double time = mistaketime / 1000 / 60 / 60 / 24;
//                time = Math.abs(time);
//                if(StringIsempty.isallempty(uid) || StringIsempty.isallempty(userType))
//                    GeneralResult.general(resp, list, 10002, 0);
//                else if(time <= ConstantUtil.LONGTIME){
//                    req.setAttribute("uid", uid);
//                    req.setAttribute("type", type);
//                    userTokenMap.put("time", timestamp + "");
//                    RedisCash.redisMap("life" + token, userTokenMap);
        for (int i = 0; i < upload.length; i++) {
            MultipartFile mf = upload[i];
            if (mf.isEmpty()) {
                continue;
            }
            byte[] s = mf.getBytes();
            if (!ImgType.isImageBmp(s) && !ImgType.isImageJpeg(s) && !ImgType.isImagePng(s)) {
                GeneralResult.general(resp, list, 10004, 0);
                return;
            }
        }
        for (int i = 0; i < upload.length; i++) {
            MultipartFile mf = upload[i];
            if (mf.isEmpty()) {
                continue;
            }
            String date = UtilDate.getShijian();
            String real = realPath + date;
            filename = UUID.randomUUID() + ".jpg";
            File image = new File(real);
            if (!image.exists() && !image.isDirectory()) {
                image.mkdirs();
            }
            FileUtils.copyInputStreamToFile(mf.getInputStream(), new File(real, filename));
            String fileurl = "";
//            if ("1".equals(type)) {
//                String realpath = real + "compress/";
//                image = new File(realpath);
//                if (!image.exists() && !image.isDirectory()) {
//                    image.mkdirs();
//                }
//                ImgCompress.upload(real + filename, realpath + filename);
//                path = real + "compress/" + filename;
//                fileurl = src + date + "compress/" + filename;
//            } else {
//                path = real + filename;
//                fileurl = src + date + filename;
//            }
//            InputStream in = new FileInputStream(path);
//            path = OssUpload.UpImgToAlisOss(fileurl, in, "image/jpeg");
//            path = filepath + fileurl;
            path = real + filename;
            if("2".equals(type)) {
                Map<String, Object> map = OcrCard.getBankCardInfo(path);
                list.add(map);
            } else if("3".equals(type)) {
                Map<String, Object> map = OcrCard.getDrivingLicenseInfo(path);
                list.add(map);
            } else if("4".equals(type)) {
                Map<String, Object> map = OcrCard.getVehicleLicenseInfo(path);
                list.add(map);
            } else if("5".equals(type)) {
                List<Map<String, Object>> plate = OcrCard.getPlateLicenseInfo(path);
                list.addAll(plate);
            } else {
                Map<String, Object> map = OcrCard.getCardInfo(path, idCardSide);
                list.add(map);
            }
        }
        GeneralResult.general(resp, list, 20000, 0);
    }
//                } else
//                    GeneralResult.general(resp, list, 10002, 0); // 登录超时
//            } else
//                GeneralResult.general(resp, list, 10002, 0); // 登录超时
//        }
//    }

    public static String uploadimg(MultipartFile[] shopimg, String src, String realPath, String date, String basePath) {
        if (shopimg == null || shopimg.length <= 0)
            return "";
        String showimg = "";
        for (int i = 0; i < shopimg.length; i++) {
            MultipartFile mf = shopimg[i];
            if (mf.isEmpty()) {
                continue;
            }
//            String date = UtilDate.getShijian();
            String real = realPath + date;
            String filename = ValueJude.getUuid() + ".jpg";
            File image = new File(real);
            if (!image.exists() && !image.isDirectory()) {
                image.mkdirs();
            }
            try {
                Upload.upload(mf, real, filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String fileurl = basePath + src + date + filename;
//            FileUtils.copyInputStreamToFile(mf.getInputStream(), new File(real, filename));
//            String fileurl = "";
//            String path = real + filename;
//            fileurl = src + date + filename;
//            InputStream in = new FileInputStream(path);
////            OssUpload.UpImgToAlisOss(fileurl, in, "image/jpeg");
            if (i == shopimg.length - 1)
                showimg += fileurl;
            else
                showimg += fileurl + ",";
        }
        return showimg;
    }

    public static String uploadimg(List<MultipartFile> shopimg, String src, String realPath, String date, String basePath) {
        if (shopimg == null || shopimg.size() <= 0)
            return "";
        String showimg = "";
        for (int i = 0; i < shopimg.size(); i++) {
            MultipartFile mf = shopimg.get(i);
            if (mf.isEmpty()) {
                continue;
            }
            String real = realPath + date;
            String filename = ValueJude.getUuid() + ".jpg";
            File image = new File(real);
            if (!image.exists() && !image.isDirectory()) {
                image.mkdirs();
            }
            try {
                Upload.upload(mf, real, filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String fileurl = basePath + src + date + filename;
            if (i == shopimg.size() - 1)
                showimg += fileurl;
            else
                showimg += fileurl + ",";
        }
        return showimg;
    }
}
